package com.hgw.ossdemo.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.hgw.ossdemo.common.FileResult;
import com.hgw.ossdemo.service.OssUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description: OSS 文件上传
 *
 * @author itLaboratory-yanAn
 * @date 2022/10/7 19:26
 */
@Service
public class OssUploadServiceImpl implements OssUploadService {

    @Value(value = "${oss.endpoint}")
    private String endpoint;
    @Value(value = "${oss.accessKeyId}")
    private String accessKeyId;
    @Value(value = "${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value(value = "${oss.bucketName}")
    private String bucketName;

    @Override
    public FileResult upload(MultipartFile multipartFile, String dir) {
        // 创建返回体
        FileResult fileResult = new FileResult();

        OSS ossClient = null;
        try {
            // 1. 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)) {
                // 若 bucket 不存在，则动态创建一个
                ossClient.createBucket(bucketName);
                // 设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            // 2. 获取文件上的流
            InputStream inputStream = multipartFile.getInputStream();
            // 3. 构建日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String dataPath = dateFormat.format(new Date());
            // 4. 获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;
            // 5. 拼接路径
            String fileUrl = dir + "/" + dataPath + "/" + fileName;
            // 6. 推送至OSS
            ossClient.putObject(bucketName, fileUrl, inputStream);
            // 7. 封装返回体信息
            fileResult.setUrl("https://" + bucketName + "." + "oss-cn-hangzhou.aliyuncs.com/" + fileUrl);
            fileResult.setPath(fileUrl);
            fileResult.setSize(multipartFile.getSize());
            fileResult.setFileName(fileName);
            fileResult.setExt(suffix);
            fileResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            fileResult.setSuccess(false);
        } finally {
            if (ossClient != null) {
                // 关闭 ossClient
                ossClient.shutdown();
            }
        }
        return fileResult;
    }

}
